package com.yunc.base.security.config;

import com.yunc.base.security.filter.JWTAuthenticationEntryPoint;
import com.yunc.base.security.filter.JWTAuthorizationFilter;
import com.yunc.base.security.service.UserDetailsServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * 提供基于web的security
 * spring security自己有一个叫FilterChainProxy代理类
 * security默认会为我们创建一个默认WebSecurityConfigurerAdapter，他拦截所有的http请求(/**),且这个Order的值是：SecurityProperties.BASIC_AUTH_ORDER
 * WebSecurityConfigurerAdapter与ResourceServerConfigurerAdapter同时在的话且都配置了处理url为：/api/**，默认是后者会生效
 * 可以看到order(100),将配置放在ResourceServerConfigurerAdapter中
 *
 * @author congcong tao
 * @create 2019/6/26 9:04
 */
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private final PermitAllSecurityConfig permitAllSecurityConfig;
    private final UserDetailsServiceImpl userDetailsService;

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 配置web端用户
        auth.userDetailsService(userDetailsService)
            .passwordEncoder(bCryptPasswordEncoder());
    }

    /**
     * 默认配置
     * http.csrf().disable()
     *                 .authorizeRequests().anyRequest().authenticated()
     *                 .and().httpBasic();
     *
     * isAuthenticated()       Returns true if the user is not anonymous
     * isFullyAuthenticated()  Returns true if the user is not an anonymous or a remember-me user
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
                .authorizeRequests()
                .antMatchers("/sysUser/login", "/sysUser/resetPassword").anonymous()
                .antMatchers("/test/**", "/api/**", "/qrcode/shareQrCode").permitAll() // 调用api不需要拦截
                .antMatchers("/swagger-resources/**", "/v2/api-docs", "/swagger-ui.html").permitAll() // swagger配置
                .anyRequest().authenticated()
                .and()
                .apply(permitAllSecurityConfig)
                .and()
                /*.addFilter(new JWTAuthenticationFilter(authenticationManager()))*/
                .addFilter(new JWTAuthorizationFilter(authenticationManager()))
                // 不需要session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                // 加一句这个
                .exceptionHandling().authenticationEntryPoint(new JWTAuthenticationEntryPoint());
    }

    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers("/css/**", "/lib/**", "/image/**", "/script/**", "/favicon.ico",
                "/common/**", "/example/**", "/system/**", "/error.html", "/home.html", "/index.html", "/login.html",
                "/password.html", "/register.html", "/reset.html");
    }

}
